package com.foreverwin.jzymes.report.rate.service.impl;

import com.foreverwin.jzymes.common.service.ISiteAdviceService;
import com.foreverwin.jzymes.framework.util.I18nUtil;
import com.foreverwin.jzymes.production.fqc.domain.FqcCheck;
import com.foreverwin.jzymes.production.fqc.enums.CheckResultEnum;
import com.foreverwin.jzymes.report.fqc.mapper.FqcCheckReportMapper;
import com.foreverwin.jzymes.report.rate.mapper.FQCrateReportMapper;
import com.foreverwin.jzymes.report.rate.service.FQCrateReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class FQCrateReportServiceImpl implements FQCrateReportService {

    @Autowired
    ISiteAdviceService siteAdviceService;
    @Autowired
    FqcCheckReportMapper fqcCheckReportMapper;
    @Autowired
    FQCrateReportMapper fqCrateReportMapper;

    @Override
    public Map<String, Object> FQCrateReport(Map<String, Object> jsonMap) {
         String site = (String)jsonMap.get("site");
        String itemBo = (String)jsonMap.get("itemBo");
        String startDate = (String)jsonMap.get("startDate");
        String endDate = (String)jsonMap.get("endDate");
        /**检查字段*/
        Assert.hasText( itemBo , I18nUtil.getI18nText("common.itemNotBlank"));
        Assert.hasText( startDate , I18nUtil.getI18nText("report.rate.startDate"));
        Assert.hasText( endDate , I18nUtil.getI18nText("report.rate.endDate"));
        siteAdviceService.existSite( site );

        Date start = null;
        Date end = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
           start = sdf.parse( startDate );
           end = sdf.parse( endDate );
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Map<String,Object> returnMap = new HashMap<>();
        List<FqcCheck> fqcChecks = new ArrayList<>();

        fqcChecks = fqcCheckReportMapper.selectFqcCheckByReport( site , itemBo , start , end );
        returnMap.put("fqcChecks",fqcChecks );
        int total = fqcChecks.size();

        if ( total != 0 ){

            int returnQty = fqCrateReportMapper.findFqcQtybyResult( site ,itemBo ,start ,end , CheckResultEnum.REJECT.getValue());

            DecimalFormat decimalFormat = new DecimalFormat("0.00") ;
            float num = (float)returnQty*100/total;
            String rate = decimalFormat.format(num)+"%";

            returnMap.put("rate", rate);
            returnMap.put("returnQty",returnQty);
        }

        return returnMap;
    }
}
